#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2

count=0

def image_callback(msg):
    global count
    # 将ROS图像消息转换为OpenCV图像格式
    bridge = CvBridge()
    cv_image = bridge.imgmsg_to_cv2(msg, "bgr8")

    # 在窗口中显示图像
    cv2.imshow("Camera Image", cv_image)
    key=cv2.waitKey(1)
    # 按下"s"键保存图像
    if key == ord('s'):  # 按下"s"键（ASCII值为115）
        cv2.imwrite("../img/letter-{}.jpg".format(count), cv_image)
        rospy.loginfo("Image saved!")
        count+=1

def main():
    rospy.init_node("image_listener")
    image_topic = "/camera/color/image_raw"  # 替换为实际的相机话题名

    # 创建一个图像订阅者，指定回调函数
    rospy.Subscriber(image_topic, Image, image_callback)

    # 循环等待回调函数
    rospy.spin()


if __name__ == '__main__':
    main()
